package com.keba.basic.encrypt.handler;

import com.keba.basic.encrypt.annotation.Sensitive;
import com.keba.basic.encrypt.format.SensitiveProcessor;
import cn.hutool.core.lang.Assert;
import lombok.extern.slf4j.Slf4j;

import java.lang.annotation.Annotation;

/**
 * @author ls
 * @since 2023-07-27
 */
@Slf4j
public class CommonSensitiveHandler implements SensitiveHandler<Sensitive> {

    private SensitiveProcessor sensitiveProcessor;

    public CommonSensitiveHandler(SensitiveProcessor sensitiveProcessor) {
        Assert.notNull(sensitiveProcessor, "sensitiveProcessor could not be null");
        this.sensitiveProcessor = sensitiveProcessor;
    }

    @Override
    public Sensitive acquire(Annotation[] annotations) {
        Sensitive sensitive = null;
        for (int i = 0; i < annotations.length; i++) {
            if (annotations[i] instanceof Sensitive) {
                sensitive = (Sensitive) annotations[i];
                if (sensitive.required()) {
                    // 注解存在且required为true
                    return sensitive;
                }
            }
        }
        return null;
    }

    @Override
    public String format(String source, Sensitive annotation) {
        if (annotation.required()) {
            try {
                return sensitiveProcessor.format(source, annotation.type());
            } catch (Exception e) {
                log.error("sensitive fail: {}, source field value: {}", e.getMessage(), source);
            }
        }
        return source;
    }
}
